<template>
  <div class="bilibili-layout">
    <!-- 视频标题移出播放器区域，放到外面 -->
    <div class="video-header-outside">
      <h2 class="video-title">{{ courseTitle }}</h2>
      <div class="video-meta">
        <span class="meta-item">播放量：{{ courseViewCount }}次</span>
        <span class="meta-dot">·</span>
        <span class="meta-item">更新于：{{ courseModifyTime.split('T')[0] }}</span>
      </div>
    </div>

    <div class="main-content">
      <!-- 播放器区域 -->
      <div class="video-wrapper">
        <div id="J_prismPlayer" class="prism-player"></div>
      </div>

      <!-- 右侧边栏 -->
      <div class="sidebar">
        <div class="up-card">
          <div class="up-header">
            <img :src="teacherAvatar" class="up-avatar"/>
            <div class="up-info">
              <h3 class="up-name">{{ teacherName }}</h3>
              <p class="up-desc">{{ teacherCareer }}</p>
            </div>
          </div>
        </div>

        <div class="section-list">
          <h3 class="list-title">课程（共{{ sections.length }}节）</h3>
          <ul class="sections">
            <li
              v-for="(section, index) in sections"
              :key="index"
              class="section-item"
              :class="{ active: currentSection === index }"
              @click="switchSection(index)"
            >
              <span class="section-index">第{{ index + 1 }}节</span>
              <span class="section-title">{{ section.sectionTitle }}</span>
              <!--              <span class="section-duration">{{ section.duration }}</span>-->
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import videoApi from '@/api/video'

export default {
  layout: 'default',
  async asyncData({ params, query,error }) {
    try {
      const response = await videoApi.getPlayAuth(params.vid)
      const data = response.data.data

      // 从query里获取当前节索引，默认0
      const currentSection = parseInt(query.section) || 0

      return {
        vid: params.vid,
        playAuth: data.playAuth,
        courseTitle: data.courseTitle,
        courseViewCount: data.courseViewCount,
        courseModifyTime: data.courseModifyTime,
        teacherAvatar: data.teacherAvatar,
        teacherName: data.teacherName,
        teacherCareer: data.teacherCareer,
        sections: Array.isArray(data.sections) ? data.sections : [],
        currentSection
      }
    } catch (e) {
      error({ statusCode: 500, message: '获取视频播放凭证失败' })
    }
  },
  data() {
    return {
      // currentSection: 0,
      player: null
    }
  },
  mounted() {
    // 加载播放器脚本
    if (!window.Aliplayer) {
      const script = document.createElement('script')
      script.src = 'https://g.alicdn.com/de/prismplayer/2.8.1/aliplayer-min.js'
      script.onload = () => {
        this.initPlayer()
      }
      document.body.appendChild(script)
    } else {
      this.initPlayer()
    }
  },
  methods: {
    async initPlayer() {
      const currentVid = this.sections[this.currentSection].videoSourceId || this.vid
      try {
        const res = await videoApi.getPlayAuth(currentVid)
        // alert('error')
        const playAuth = res.data.data.playAuth
        // alert(playAuth)
        // 销毁旧播放器并清空DOM
        if (this.player) {
          this.player.dispose()
          this.player = null
        }
        const container = document.getElementById('J_prismPlayer')
        if (container) {
          container.innerHTML = '' // 必须清空播放器容器内容
        }

        // 确保DOM被清空再初始化
        setTimeout(() => {
          this.player = new window.Aliplayer({
            id: 'J_prismPlayer',
            vid: currentVid,
            playauth: playAuth,
            encryptType: '1',
            width: '100%',
            height: '100%',
            autoplay: true,
            useH5Prism: true
          }, () => {
            console.log('播放器已切换至 vid:', currentVid)
          })
        }, 100)
      } catch (error) {
        // alert('error')
        console.error('获取播放凭证失败：', error)
      }
    },
    switchSection(index) {
      if (index === this.currentSection)
        return
      // alert(this.sections[index].videoSourceId)
      this.currentSection = index
      this.$router.replace({
        query: {
          ...this.$route.query,
          section: index
        }
      })
      // 重新加载播放器和播放凭证
      this.initPlayer()
    }
  },
  beforeDestroy() {
    if (this.player) {
      this.player.dispose()
    }
  }
}
</script>

<style>
@import url('https://g.alicdn.com/de/prismplayer/2.8.1/skins/default/aliplayer-min.css');

.bilibili-layout {
  max-width: 1480px;
  margin: 0 auto;
  padding: 20px;
  background: #f4f4f4;
  min-height: 100vh;
}

.video-header-outside {
  margin-bottom: 12px;
}

.video-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0 0 8px 0;
  line-height: 1.4;
}

.video-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
  font-size: 14px;
  margin-bottom: 8px;
}

.meta-dot {
  font-size: 6px;
  margin-top: -2px;
}

.main-content {
  display: grid;
  grid-template-columns: 72% 1fr;
  gap: 24px;
}

.video-wrapper {
  position: relative;
  padding-top: 56.25%;
  height: 0;
  overflow: hidden;
  border-radius: 8px;
  background: #000;
}

.prism-player {
  position: absolute !important;
  top: 0;
  left: 0;
  width: 100% !important;
  height: 100% !important;
  border-radius: 8px;
}

.sidebar {
  position: sticky;
  top: 20px;
  align-self: start;
}

.up-card {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.up-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.up-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover;
  border: 1px solid #ddd;
}

.up-name {
  font-size: 16px;
  font-weight: 500;
  color: #212121;
  margin: 0;
}

.up-desc {
  color: #666;
  font-size: 13px;
  margin: 4px 0 0 0;
}

.section-list {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  height: 480px !important;
  display: flex;
  flex-direction: column;
}

.list-title {
  padding: 12px 16px;
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #212121;
  border-bottom: 1px solid #f0f0f0;
  flex-shrink: 0;
}

.sections {
  list-style: none;
  padding: 0;
  margin: 0;
  overflow-y: auto;
  max-height: 430px;
}

.section-item {
  padding: 12px 16px;
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  transition: background 0.2s;
}

.section-item:hover {
  background: #f5f5f5;
}

.section-item.active {
  background: #e5f3ff;
}

.section-item.active .section-title {
  color: #00a1d6;
}

.section-index {
  flex-shrink: 0;
  width: 60px;
  color: #999;
  font-size: 14px;
}

.section-title {
  flex: 1;
  color: #212121;
  font-size: 14px;
  line-height: 1.5;
}

.section-duration {
  flex-shrink: 0;
  color: #999;
  font-size: 13px;
}
</style>
